import { defineConfig, loadEnv, ConfigEnv, UserConfig } from "vite";
import { resolve } from "path";
import react from "@vitejs/plugin-react";
import { visualizer } from "rollup-plugin-visualizer";
import viteCompression from "vite-plugin-compression";
import { isDevFn, wrapperEnv } from "./src/utils/getEnv";
import { createHtmlPlugin } from "vite-plugin-html";

// https://vitejs.dev/config/
export default defineConfig((configEnv: ConfigEnv): UserConfig => {
	const env = loadEnv(configEnv.mode, process.cwd());
	const viteEnv = wrapperEnv(env);

	const isDev = isDevFn(configEnv.mode);

	console.log("=========env:", viteEnv);

	return {
		// alias config
		resolve: {
			alias: {
				"@": resolve(__dirname, "./src")
			}
		},
		// global css
		css: {
			preprocessorOptions: {
				less: {
					// modifyVars: {
					// 	"primary-color": "#1DA57A",
					// },
					javascriptEnabled: true,
					additionalData: `@import "@/styles/var.less";`
				}
			}
		},
		server: {
			host: "0.0.0.0", // 服务器主机名，如果允许外部访问，可设置为"0.0.0.0"
			port: viteEnv.VITE_PORT,
			open: viteEnv.VITE_OPEN,
			cors: true,
			// https: false,
			proxy: {
				"/admin": {
					target: "https://api.sit.onefishx.com",
					changeOrigin: true,
					rewrite: path => path.replace(/^\/admin/, "/admin")
				},
				"/api": {
					target: "https://api.sit.onefishx.com",
					changeOrigin: true,
					rewrite: path => path.replace(/^\/api/, "/api")
				}
			}
		},
		plugins: [
			react(),
			createHtmlPlugin({
				inject: {
					data: {
						title: viteEnv.VITE_GLOB_APP_TITLE
					}
				}
			}),
			// * 是否生成包预览
			viteEnv.VITE_PREVIEW_REPORT &&
				visualizer({
					open: true, //注意这里要设置为true，否则无效
					filename: "preview.html",
					gzipSize: true,
					brotliSize: true
				}),
			// * gzip compress
			viteEnv.VITE_BUILD_GZIP &&
				viteCompression({
					verbose: true,
					disable: false,
					threshold: 10240,
					algorithm: "gzip",
					ext: ".gz"
				})
		],
		esbuild: {
			pure: viteEnv.VITE_DROP_CONSOLE ? ["console.log", "debugger"] : []
		},
		optimizeDeps: {
			include: ["qrcode.react"]
		},
		// build configure
		build: {
			outDir: "dist",
			minify: "esbuild",
			rollupOptions: {
				output: {
					// Static resource classification and packaging
					chunkFileNames: "assets/js/[name]-[hash].js",
					entryFileNames: "assets/js/[name]-[hash].js",
					assetFileNames: info => {
						const imagesReg = /\.(png|webp|jpeg|ico|jpg)$/;

						if (imagesReg.test(info?.name)) {
							return "assets/images/[name]-[hash].[ext]";
						}

						return "assets/[ext]/[name]-[hash].[ext]";
					}
				}
			}
		}
	};
});
